<?php
/**
 * Created by PhpStorm.
 * User: ewen
 * Date: 2019-12-31
 * Time: 17:25
 */

namespace app\admin\controller;


use app\common\model\XkAdminAuth;
use app\common\model\XkAdminRole;
use think\captcha\Captcha;
use think\Loader;
use app\common\model\XkAdmin as adminModel;

class Admin extends Base
{

    /**
     * 登录页面
     * @return mixed
     */
    public function login()
    {
        //  判断是否为已经登录状态
        session('adminInfo')['id'] > 0 && $this->success(lang('already log in'), U('Admin/Index/index'));
        if (IS_POST) {
            //  验证验证码
            !$this->checkVerifyCode(I('post.verifyCode')) && ajaxReturn(['status' => 0, 'msg' => lang('verify code error')]);

            //  表单验证规则
            $validate = Loader::validate('Admin');
            if (!$validate->scene('login')->check(['adminName' => I('post.adminName'), 'adminPwd' => I('post.adminPwd')])) {
                backError($validate->getError());
            } else {
                //  验证账号密码
                adminModel::checkNamePwd(I('post.adminName'), I('post.adminPwd'));
            }
        }
        return $this->fetch();
    }

    /**
     * 验证码
     */
    public function verifyCode()
    {
        $config = [
            // 验证码字体大小
            'fontSize' => 35,
            // 验证码位数
            'length' => 4,
            // 关闭验证码杂点
            'useNoise' => true,
            //  高度
            'imageH' => 70,
            //  宽度
//            'imageW'      =>    100
            //  是否画混淆曲线
            'useCurve' => true
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }

    /**
     * 验证码校验
     * @param $code
     * @param string $id
     * @return bool
     */
    function checkVerifyCode($code, $id = '')
    {
        $captcha = new Captcha();
        return $captcha->check($code, $id);
    }

    /**
     * 退出登录
     */
    public function logOut()
    {
        session(null);
        $this->success(lang('log out successfully, now jumping...'), U('Admin/admin/login'));
    }

    /**
     * 管理员信息
     * @return mixed
     */
    public function baseInfo()
    {
        if (IS_POST) {
            $adminAvatar = I('post.adminAvatar');
            $adminPhone = I('post.adminPhone');
            $adminEmail = I('post.adminEmail');
            //  修改管理员信息
            $res = adminModel::where(['id' => session('adminInfo')['id']])->save([
                'adminAvatar' => $adminAvatar,
                'adminPhone' => $adminPhone,
                'adminEmail' => $adminEmail,
                'updateTime' => time()
            ]);
            //  重置管理员信息
            $adminInfo = adminModel::alias('a')
                ->field('a.*,b.roleName')
                ->join('admin_role b', 'a.roleID = b.id', 'left')
                ->where(['a.id' => session('adminInfo')['id'], 'a.isDel' => 0])->find();
            session('adminInfo', $adminInfo);
            $res && clearCacheByKey(adminModel::CACHE_ADMIN_ADMIN_LIST);
            $res ? backSuccess($adminAvatar, lang('edit successfully')) : backError(lang('edit failed'));
        }
        return $this->fetch();
    }

    /**
     * 修改管理员密码
     * @return mixed
     */
    public function changePwd()
    {
        if (IS_POST) {
            $oldPwd = I('post.oldPwd');
            $newPwd = I('post.newPwd');
            $reNewPwd = I('post.reNewPwd');
            //  表单验证规则
            $validate = Loader::validate('Admin');
            if (!$validate->scene('changePwd')->check(['oldPwd' => $oldPwd, 'newPwd' => $newPwd, 'reNewPwd' => $reNewPwd])) {
                backError($validate->getError());
            } else {
                //  验证账号密码
                adminModel::changePwd($oldPwd, $newPwd);
            }
        }
        return $this->fetch();
    }

    /**
     * 角色管理
     * @return mixed
     */
    public function roleList()
    {
        $hasAuth = checkAuth(session('adminInfo')['id'], 9);
        if (!$hasAuth) return $this->fetch('public/denied');

        $list = XkAdminRole::where(['isDel' => 0])->paginate(10);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 编辑角色
     * @return mixed
     */
    public function editRole()
    {
        $hasAuth = checkAuth(session('adminInfo')['id'], 8);
        if (!$hasAuth) return $this->fetch('public/denied');

        $roleID = I('post.roleID/d');
        $roleInfo = XkAdminRole::where(['id' => $roleID])->find();
        $roleInfo['authIDs'] = explode(',', $roleInfo['authIDs']);
        $this->assign('roleInfo', $roleInfo);
        $allAuth = XkAdminAuth::getAuthList();
        $this->assign('allAuth', $allAuth);
        if (IS_POST) {
            $roleName = I('post.roleName');
            $roleID = I('post.roleID/d');
            $authIDs = isset($_POST['authIDs']) ? $_POST['authIDs'] : [];
            $authIDs = array_unique(array_filter($authIDs));
            !$roleID && ajaxReturn(['status' => 0, 'msg' => lang('invalid role id')]);
            !$roleName && ajaxReturn(['status' => 0, 'msg' => lang('invalid role name')]);
            $res = XkAdminRole::where(['id' => $roleID])->save([
                'roleName' => $roleName,
                'authIDs' => implode(',', $authIDs),
                'updateTime' => time()
            ]);
            $res ? backSuccess() : backError();
        }
        return $this->fetch();
    }

    /**
     * 新增角色
     */
    public function addRole()
    {
        $hasAuth = checkAuth(session('adminInfo')['id'], 7);
        if (!$hasAuth) return $this->fetch('public/denied');

        $allAuth = XkAdminAuth::getAuthList();
        $this->assign('allAuth', $allAuth);

        if (IS_POST) {
            $roleName = I('post.roleName');
            $authIDs = isset($_POST['authIDs']) ? $_POST['authIDs'] : [];
            $authIDs = array_unique(array_filter($authIDs));
            !$roleName && ajaxReturn(['status' => 0, 'msg' => lang('invalid role')]);
            count($authIDs) == 0 && ajaxReturn(['status' => 0, 'msg' => lang('select at least one permission')]);
            $res = XkAdminRole::add([
                'roleName' => $roleName,
                'authIDs' => implode(',', $authIDs),
                'addTime' => time()
            ]);
            $res ? backSuccess() : backError();
        }

        return $this->fetch();
    }

    /**
     * 管理员列表
     * @return mixed
     */
    public function adminList()
    {
        $hasAuth = checkAuth(session('adminInfo')['id'], 4);
        if (!$hasAuth) return $this->fetch('public/denied');

        $list = adminModel::getAdmins();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 新增管理员
     * @return mixed
     */
    public function addAdmin()
    {
        $hasAuth = checkAuth(session('adminInfo')['id'], 2);
        if (!$hasAuth) return $this->fetch('public/denied');

        $roles = XkAdminRole::where(['isDel' => 0])->select();
        $this->assign('roles', $roles);

        if (IS_POST) {
            $roleID = I('post.roleID/d');
            $adminName = I('post.adminName');
            $adminPwd = I('post.adminPwd');
            $adminAvatar = I('post.adminAvatar');
            $adminPhone = I('post.adminPhone');
            $adminEmail = I('post.adminEmail');
            //  表单验证规则
            $validate = Loader::validate('Admin');
            if (!$validate->scene('addAdmin')->check(['adminName' => $adminName, 'adminPwd' => $adminPwd, 'roleID' => $roleID, 'checkAdminName' => $adminName])) {
                backError($validate->getError());
            } else {
                adminModel::addAdmin($adminName, $adminPwd, $roleID, $adminAvatar, $adminPhone, $adminEmail);
            }
        }

        return $this->fetch();
    }

    /**
     * 编辑管理员
     * @return mixed
     */
    public function editAdmin()
    {
        $hasAuth = checkAuth(session('adminInfo')['id'], 3);
        if (!$hasAuth) return $this->fetch('public/denied');

        $adminID = I('adminID');

        if ($adminID == 1) {
            $this->assign('tips', [
                'title' => '',
                'content' => lang('super admin can not be edited'),
                'href' => ''
            ]);
            return $this->fetch('public/error');
        }

        $adminInfo = adminModel::getAdmins(['a.isDel' => 0, 'a.id' => $adminID]);
        $this->assign('adminInfo', $adminInfo[0]);

        $roles = XkAdminRole::where(['isDel' => 0])->select();
        $this->assign('roles', $roles);

        if (IS_POST) {
            $roleID = I('post.roleID/d');
            $adminName = I('post.adminName');
            $adminPwd = I('post.adminPwd');
            $adminAvatar = I('post.adminAvatar');
            $adminPhone = I('post.adminPhone');
            $adminEmail = I('post.adminEmail');
            $adminID = I('post.adminID/d');
            //  表单验证规则
            $validate = Loader::validate('Admin');
            if (!$validate->scene('editAdmin')->check(['adminName' => $adminName, 'adminPwdEdit' => $adminPwd, 'roleID' => $roleID, 'checkAdminName' => $adminName, 'adminID' => $adminID])) {
                backError($validate->getError());
            } else {
                $res = adminModel::editAdmin($adminName, $roleID, $adminID, $adminPwd, $adminAvatar, $adminPhone, $adminEmail);
                if ($adminID == session('adminInfo')['id'] && $res['status'] == 1) {
                    //  重置管理员信息
                    $adminInfo = adminModel::alias('a')
                        ->field('a.*,b.roleName')
                        ->join('admin_role b', 'a.roleID = b.id', 'left')
                        ->where(['a.id' => session('adminInfo')['id'], 'a.isDel' => 0])->find();
                    session('adminInfo', $adminInfo);
                }
                ajaxReturn($res);
            }
        }

        return $this->fetch();
    }

}